package com.chazaqdev.meatbagsorter

class MonitorFolderController {
	def servletContext

	def monitorFolderService
	
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [monitorFolderInstanceList: MonitorFolder.list(params), monitorFolderInstanceTotal: MonitorFolder.count()]
    }

    def create = {
        def monitorFolderInstance = new MonitorFolder()
        monitorFolderInstance.properties = params
        return [monitorFolderInstance: monitorFolderInstance]
    }

    def save = {
        def monitorFolderInstance = new MonitorFolder(params)
        if (monitorFolderInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'monitorFolder.label', default: 'MonitorFolder'), monitorFolderInstance.id])}"
//			monitorFolderService.startRunningFileMonitor(monitorFolderInstance, grailsAttributes.getApplicationContext().getResource("/"))
			monitorFolderService.startRunningFileMonitor(monitorFolderInstance, servletContext.getRealPath ('/'))
            redirect(action: "show", id: monitorFolderInstance.id)
        }
        else {
            render(view: "create", model: [monitorFolderInstance: monitorFolderInstance])
        }
    }

    def show = {
        def monitorFolderInstance = MonitorFolder.get(params.id)
        if (!monitorFolderInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'monitorFolder.label', default: 'MonitorFolder'), params.id])}"
            redirect(action: "list")
        }
        else {
            [monitorFolderInstance: monitorFolderInstance]
        }
    }

    def edit = {
        def monitorFolderInstance = MonitorFolder.get(params.id)
        if (!monitorFolderInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'monitorFolder.label', default: 'MonitorFolder'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [monitorFolderInstance: monitorFolderInstance]
        }
    }

    def update = {
        def monitorFolderInstance = MonitorFolder.get(params.id)
        if (monitorFolderInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (monitorFolderInstance.version > version) {
                    
                    monitorFolderInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'monitorFolder.label', default: 'MonitorFolder')] as Object[], "Another user has updated this MonitorFolder while you were editing")
                    render(view: "edit", model: [monitorFolderInstance: monitorFolderInstance])
                    return
                }
            }
            monitorFolderInstance.properties = params
            if (!monitorFolderInstance.hasErrors() && monitorFolderInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'monitorFolder.label', default: 'MonitorFolder'), monitorFolderInstance.id])}"
                redirect(action: "show", id: monitorFolderInstance.id)
            }
            else {
                render(view: "edit", model: [monitorFolderInstance: monitorFolderInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'monitorFolder.label', default: 'MonitorFolder'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def monitorFolderInstance = MonitorFolder.get(params.id)
        if (monitorFolderInstance) {
            try {
                monitorFolderInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'monitorFolder.label', default: 'MonitorFolder'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'monitorFolder.label', default: 'MonitorFolder'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'monitorFolder.label', default: 'MonitorFolder'), params.id])}"
            redirect(action: "list")
        }
    }
	
	
	private static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i=0; i<children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
	
		// The directory is now empty so delete it
		return dir.delete();
	}
	
	private void copyPhotoToDir(Photo photo, File dir) {
		try {
			File f = new File(servletContext.getRealPath ('/') + photo.savedToFolder + "/" + photo.id + "_orig.jpeg")
			InputStream is = new FileInputStream(f)
			
			//Copy original
			FileOutputStream fos = new FileOutputStream(dir.absolutePath + "/" + photo.id + ".jpeg")
			byte[] b = new byte[f.length()]
			is.read(b)
			fos.write (b)
			fos.close()
		} catch (Exception e) {
			e.printStackTrace()
		}
	}
	
	def exportToDesktop = {
		String desktopPath = "";
		try{
			desktopPath = System.getProperty("user.home") + "/Desktop";
			desktopPath = desktopPath.replace("\\", "/");
		}catch (Exception e){
			System.out.println("Exception caught ="+e.getMessage());
		}

		Participant one = Participant.findByNumber("1")
		def oneFolder = null
		if (one != null) {
			oneFolder = PhotoTag.findAllByParticipant(one)
		}
		
		File desktopDir = new File(desktopPath + "/MeatBagPicSorter")
		
		if (desktopDir.exists()) {
			deleteDir desktopDir
		}
		
		desktopDir.mkdirs()
		
		File currentParticipant
		
		for (Participant p in Participant.list()) {
			currentParticipant = new File(desktopDir.getAbsolutePath() + "/" + p.number)
			currentParticipant.mkdirs()
			
			for (PhotoTag pt in PhotoTag.findAllByParticipant (p)) {
				copyPhotoToDir (pt.photo, currentParticipant)
			}
		}
		
		
		flash.message = "Exported to " + desktopDir.absolutePath
		
		redirect(uri:"/", params: params)
		
	}
}
